package com.zerdoor.util.el;

import com.zerdoor.filter.RequestFilter;
import com.zerdoor.service.IFavoriteService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by xiaobo on 2014/11/10.
 */
public class UFunction {

        /**
         * 获取一个字符串的长度
         *
         * @author bchen
         * @date 2008-5-15
         * @param str
         * @return int
         */
        public static int getLen(String str) {
            return str.length();
        }

        /**
         * 截取字符串
         *
         * @author bchen
         * @date 2008-5-15
         * @param str
         * @param start
         * @param end
         * @return String
         */
        public static String substr(String str, int start, int end) {
            return str.substring(start, end);
        }

        /**
         * 两数相除获取整数结果
         *
         * @author bchen
         * @date 2008-5-15
         * @param first
         * @param second
         * @return int
         */
        public static int chufa(int first, int second) {
            return first / second;
        }


        /**
         * 两数相除获取整数结果
         *
         * @author zjy
         * @date 2008-5-15
         * @param code
         * @return int
         */
        public static String swapCode(String code) {

            //得到session
            HttpServletRequest request = RequestFilter.threadLocal.get();
            HttpSession session =  request.getSession();

            return String.valueOf(session.getAttribute("language"));
        }

    /**
     * 根据参数信息查找当前数据是否被收藏 如果返回favoriteId为空表示未收藏
     * @param userId
     * @param collectId
     * @param type
     * @return
     */
        public static String findFavorite(int userId,int collectId,int type){

            HttpServletRequest request = RequestFilter.threadLocal.get();

            ServletContext sc = request.getServletContext();

            ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(sc);

            IFavoriteService is = (IFavoriteService) ac2.getBean("favoriteServiceImpl");

            System.out.println("is=" + is);

            String favoriteId = "";

            try {
                favoriteId = is.findFavorite(userId,collectId,type);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return favoriteId;
        }

    /**
     * 获取该字符串最后出现位置后面的字符
     * @param input
     * @param last
     * @return
     */
    public static String subStringLastAfter(String input, String last){

        return input.substring(input.lastIndexOf(last)+last.length());
    }

}
